/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

use super::super::traits::{InitContext, InitHandler};
use config_manager::types::context::{ServerConfig, CONFIG};
use std::future::Future;
use std::pin::Pin;
use common_log::info;

const CONFIG_FILE_PATH: &str = "/etc/attestation_server/server_config.yaml";

#[derive(Debug)]
pub struct ConfigInitHandler {
    next: Option<Box<dyn InitHandler>>,
}

impl ConfigInitHandler {
    pub fn new() -> Self {
        ConfigInitHandler { next: None }
    }

    fn load_config(&self) -> Result<ServerConfig, String> {
        // Actual configuration loading logic
        info!("Loading configuration...");
        
        let config_path = std::path::PathBuf::from(CONFIG_FILE_PATH);
        CONFIG.initialize(config_path.to_str().ok_or("Invalid server_config path")?)?;
        Ok(CONFIG.get_instance()?.clone())
    }
}

impl InitHandler for ConfigInitHandler {
    fn handle<'a>(&'a self, context: &'a mut InitContext) -> Pin<Box<dyn Future<Output = Result<(), String>> + 'a>> {
        Box::pin(async move {
            let config = self.load_config()?;
            context.config = Some(config);

            if let Some(next) = &self.next {
                next.handle(context).await
            } else {
                Ok(())
            }
        })
    }

    fn set_next(&mut self, next: Box<dyn InitHandler>) {
        self.next = Some(next);
    }
}
